/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
 
/* $Id: crypt.c 3 2007-07-10 06:59:05Z kf701.ye $ */

#include "factory.h"

/**
 * @brief simple encrypt string
 *
 * Note: The key and src must be string
 * and the dest buffer must enough length as src
 *
 * @return void
 * the dest will be filled crypted string
 */
void string_encrypt(uint8_t *dest, const uint8_t *src, const uint8_t *key)
{
	int slen = strlen((const char*)src);
	int klen = strlen((const char*)key);
	int i, j=0, tmp;
	for( i=0; i<slen; i++ )
	{
		if( src[i] != key[i] )
			dest[i] = src[i] ^ key[j++];
		else
			dest[i] = key[j++];
		if( klen == j )
			j = 0;
	}
	for( i=0; i<slen && dest[i+1]; i=i+2)
	{
		tmp = dest[i];
		dest[i] = dest[i+1];
		dest[i+1] = tmp;
	}
	dest[slen] = 0;
}

/**
 * @brief simple decrypt string crypted by string_encrypt
 *
 * Note:  The key and src must be string
 * and the dest buffer must enough length as src
 *
 * @return void
 * the dest will be filled decrypted string
 */
void string_decrypt(uint8_t *dest, const uint8_t *src, const uint8_t *key)
{
	int slen = strlen((const char*)src);
	int klen = strlen((const char*)key);
	uint8_t in_src[256] = {0,};
	int i, j=0, tmp;

	memcpy(in_src, src, slen);
	for( i=0; i<slen && in_src[i+1]; i=i+2)
	{
		tmp = in_src[i];
		in_src[i] = in_src[i+1];
		in_src[i+1] = tmp;
	}
	for( i=0; i<slen; i++ )
	{
		if( in_src[i] != key[i] )
			dest[i] = in_src[i] ^ key[j++];
		else
			dest[i] = key[j++];
		if( klen == j )
			j = 0;
	}
	dest[slen] = 0;
}
